package com.alfred.mall.miaosha.biz.service.limit;

import com.alfred.mall.miaosha.api.limit.AccessLimitService;
import com.google.common.util.concurrent.RateLimiter;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.stereotype.Component;

/**
 * 秒杀前的限流.
 * 使用了Google guava的RateLimiter
 */
@Component
@Service
public class AccessLimitServiceImpl implements AccessLimitService {
    /**
     * 每秒钟只发出10个令牌，拿到令牌的请求才可以进入秒杀过程
     */
    private RateLimiter seckillRateLimiter = RateLimiter.create(10);

    /**
     * 尝试获取令牌
     *
     * @return
     */
    @Override
    public boolean tryAcquireSeckill() {
        return seckillRateLimiter.tryAcquire();
    }
}
